package com.yami.shop.discount.common.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.event.ShopChangeStatusEvent;
import com.yami.shop.discount.common.constants.DiscountStatusEnum;
import com.yami.shop.discount.common.model.Discount;
import com.yami.shop.discount.common.service.DiscountService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 店铺改变状态监听
 *
 * @Author lth
 * @Date 2021/11/22 15:04
 */
@Component("discountShopChangeStatusListener")
@AllArgsConstructor
public class ShopChangeStatusListener {

    private final DiscountService discountService;

    @EventListener(ShopChangeStatusEvent.class)
    public void discountShopChangeStatusListener(ShopChangeStatusEvent event) {
        Long shopId = event.getShopId();
        ShopStatus shopStatus = event.getShopStatus();
        if (Objects.isNull(shopId) || Objects.isNull(shopStatus)) {
            return;
        }
        if (Objects.equals(shopStatus, ShopStatus.OFFLINE)) {
            // 店铺下线时，把所有满减活动失效
            List<Long> discountIds = discountService.listIdByShopIdAndStatus(shopId, DiscountStatusEnum.RUN.getValue());
            if (CollUtil.isEmpty(discountIds)) {
                return;
            }
            // 失效活动
            discountService.update(Wrappers.lambdaUpdate(Discount.class)
                    .set(Discount::getStatus, DiscountStatusEnum.CLOSE.getValue())
                    .in(Discount::getDiscountId, discountIds)
            );
            // 清除缓存
            discountIds.forEach(discountService::removeDiscountAndItemAndProdCacheById);
            discountService.removeDiscountsAndItemsCacheByShopId(shopId);
        }
    }
}
